﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Radar.Utils
{
    public struct Line
        : IEqualityComparer<Line>
    {

        public Line(int begin, int end)
            : this()
        {
            if (begin > end) throw new ArgumentException(String.Format("Begin ({0}) cannot be higher than End ({1}).", begin.ToString(), end.ToString()));
            Begin = begin;
            End = end;
            Length = end - begin;
        }

        public int Begin;

        public int End;

        public int Length;

        #region Static methods

        static public bool operator==(Line a, Line b)
        {
            return (a.Begin == b.Begin && a.End == b.End);
        }

        static public bool operator !=(Line a, Line b)
        {
            return (a.Begin != b.Begin || a.End != b.End);
        }

        static public Line? GetIntersection(Line a, Line b)
        {
            if (a.Begin > b.Begin)
            {
                // swap to reduce possible scenarios
                Line t = a;
                a = b;
                b = t;
            }

            if (a.End < b.Begin)
            {
                // no intersection at all:
                // a: -----
                // b:       -----
                return null;
            }
            else
            {
                // a.End >= b.Begin -> is intersection
                if (a.End < b.End)
                {
                    // a and b share only a subsection of either Line
                    // a: -----
                    // b:    -----
                    return new Line(b.Begin, a.End);
                }
                else
                {
                    // b sits entirely inside a, so b = intersection
                    // a: --------
                    // b:   ----
                    return b;
                }
            }
        }

        #endregion


        #region IEqualityComparer<Line> Members

        public override bool Equals(object obj)
        {
            if (obj is Line)
            {
                return this == (Line)obj;
            }
            else
            {
                return false;
            }
        }

        public bool Equals(Line x, Line y)
        {
            return x == y;
        }

        public override int GetHashCode()
        {
            return Begin.GetHashCode() + End.GetHashCode();
        }

        public int GetHashCode(Line obj)
        {
            return Begin.GetHashCode() + End.GetHashCode();
        }

        #endregion
    }
}
